package com.jingjing.control.common;

import com.jingjing.model.common.Ueditor;
import com.jingjing.model.common.UeditorConfig;
import com.jingjing.model.note.Note;
import com.jingjing.model.user.User;
import com.jingjing.service.common.UeditorService;
import com.jingjing.service.note.NoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: jingjing
 * @description: 百度ueditor相关控制
 * @author: 何伟
 * @create: 2019-03-26 18:42
 **/

@Controller
public class UeditorController {

    Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    UeditorService ueditorService;
    @Autowired
    NoteService noteService;

    @RequestMapping("/ueditorpage")
    private String ueditorPage(){
        return "ueditor-page";
    }


    @RequestMapping("/ueditoredit")
    private String ueditorEdit( Long noteid,ModelMap modelMap){

        Note note=noteService.getNoteById(noteid);
        modelMap.addAttribute("note",note);
        return "ueditor-page";
    }

    @RequestMapping(value="/ueditor")
    @ResponseBody
    public String ueditor(HttpServletRequest request) {

        return UeditorConfig.UEDITOR_CONFIG;
    }

    @RequestMapping(value="/imgUpload")
    @ResponseBody
    public Ueditor imgUpload(MultipartFile upfile,HttpServletRequest request, HttpSession session) throws IOException{

        Ueditor ueditor = uploadImg(upfile,request,session);
        return ueditor;
    }

    public Ueditor uploadImg(MultipartFile file,
                            HttpServletRequest request, HttpSession session) throws IOException {

        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        Ueditor ueditor = new Ueditor();
        User user = (User)session.getAttribute("user");

        String webPath=request.getSession().getServletContext().getRealPath("");
        String path = webPath+"WEB-INF/classes/static/upload/"+"/image/"+user.getId();

        String ct = file.getContentType() ;
        String fileType = "";
        if (ct.indexOf("/")>0) {
            fileType = ct.substring(ct.indexOf("/")+1);
        }

        String fileName = sdf.format(new Date()) + "." + fileType;

        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        File targetFile2 = new File(path+"/"+fileName);
        if (!targetFile2.exists()) {
            targetFile2.createNewFile();
        }
        // 保存
        try {
            file.transferTo(targetFile2);
            ueditor.setState("SUCCESS");
        } catch (Exception e) {
            e.printStackTrace();
            ueditor.setState("ERROR");
        }
        ueditor.setTitle(fileName);
        ueditor.setOriginal(fileName);
        ueditor.setUrl("static/upload/image/"+user.getId()+ File.separator+fileName);
        return ueditor;
    }

    @RequestMapping("savenote")
    @ResponseBody
    public Map saveNote(@RequestBody Note note,HttpSession session, HttpServletRequest request/*,ModelMap modelMap*/){

        note.setCreateDate(new Date());
        Map modelMap=new HashMap<String,String>();

        try{
            noteService.saveNote(note);
        }catch (Exception e){
            logger.error("删除笔记出错："+e.getMessage());
            modelMap.put("ErrorCode","500");
            modelMap.put("ErrorTitle","服务器异常");
            modelMap.put("ErrorMsg","删除笔记失败！");
            modelMap.put("success","no");
            return modelMap;
        }
        modelMap.put("success","yes");
        return modelMap;
    }

    @RequestMapping("updatenote")
    @ResponseBody
    public Map updateNote(@RequestBody Note note,HttpSession session, HttpServletRequest request){

        Map modelMap=new HashMap<String,String>();

        try{
            noteService.updateContent(note.getId(),note.getContent());
        }catch (Exception e){
            logger.error("删除笔记出错："+e.getMessage());
            modelMap.put("ErrorCode","500");
            modelMap.put("ErrorTitle","服务器异常");
            modelMap.put("ErrorMsg","删除笔记失败！");
            modelMap.put("success","no");
            return modelMap;
        }
        modelMap.put("success","yes");
        return modelMap;
    }
}
